package test.queue;

import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author bingo
 * @Description
 * @Date 2018/8/24
 */
public class Main {

    private LinkedBlockingQueue queue = new LinkedBlockingQueue();

    public synchronized void add(int value){
        if(queue.size()>50) {
            if (queue.size() >= 100) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            notify();
        }
        queue.add(value);
        System.out.println(Thread.currentThread().getName()+"一共"+queue.size()+"条数据");
    }

    public synchronized void remove(){

        if(queue.size()<=50){
                notify();
                }
        try {
            queue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"一共"+queue.size()+"条数据");
    }

    public static void main(String[] args) {
        Main main = new Main();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Random random = new Random();
                    main.add( random.nextInt(10));
                }


            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    main.remove();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    main.remove();
                }
            }
        }).start();
    }



}
